package controllers

import (
	"encoding/json"
	"errors"
	"fmt"

	md "gitee.com/countpoison/youbei/models"
	jobs "gitee.com/countpoison/youbei/utils/jobs"
	"github.com/astaxie/beego/toolbox"
)

func (c *MainController) AddSshtask() {
	ob := new(md.SshTask)
	c.APIReturn(500, "解析失败", json.Unmarshal(c.Ctx.Input.RequestBody, ob))
	c.APIReturn(500, "录入失败", ob.Add())
	if len(ob.RS) > 0 {
		c.APIReturn(500, "添加任务失败6", md.RemoteStorageToTaskFunc(ob.ID, ob.RS))
	}
	toolbox.AddTask(ob.ID, toolbox.NewTask(ob.ID, ob.Crontab, jobs.SshJobs(ob.ID)))
	c.APIReturn(200, "录入成功", nil)
}

func (c *MainController) UpdateSshtask() {
	ob := new(md.SshTask)
	c.APIReturn(500, "解析失败", json.Unmarshal(c.Ctx.Input.RequestBody, ob))
	ob.ID = c.Ctx.Input.Param(":id")
	c.APIReturn(500, "修改失败", ob.Update())
	c.APIReturn(500, "修改任务失败6", md.RemoteStorageToTaskFunc(ob.ID, ob.RS))
	toolbox.AddTask(ob.ID, toolbox.NewTask(ob.ID, ob.Crontab, jobs.SshJobs(ob.ID)))
	c.APIReturn(200, "修改成功", nil)
}

func (c *MainController) DeleteSshtask() {
	ob := new(md.SshTask)
	ob.ID = c.Ctx.Input.Param(":id")
	c.APIReturn(500, "删除失败", ob.Delete())
	c.APIReturn(200, "删除成功", nil)
}

func (c *MainController) SshtaskList() {
	sshtasks := []md.SshTask{}

	c.APIReturn(500, "获取失败", md.Localdb().Find(&sshtasks))
	title, err := md.Localdb().Count(new(md.SshTask))
	c.APIReturn(500, "获取总数失败", err)
	rep := map[string]interface{}{"count": title, "data": sshtasks}
	c.APIReturn(200, "获取成功", rep)
}

func (c *MainController) GetSshtask() {
	sshtask := new(md.SshTask)
	sshtask.ID = c.Ctx.Input.Param(":id")
	if bol, err := md.Localdb().Get(sshtask); err != nil {
		c.APIReturn(500, "获取失败", err)
	} else {
		if !bol {
			c.APIReturn(500, "任务不存在", errors.New("任务不存在"))
		}
	}
	if rstr, err := getRS(sshtask.ID); err != nil {
		c.APIReturn(500, "获取失败", err)
	} else {
		sshtask.RS = rstr
	}
	c.APIReturn(200, "获取成功", sshtask)
}

func getRS(tid string) ([]string, error) {
	rs := []md.RemoteStorageToTask{}
	if err := md.Localdb().Where("tid=?", tid).Find(&rs); err != nil {
		return []string{}, err
	}
	rstr := []string{}
	if len(rs) > 0 {
		for _, s := range rs {
			rstr = append(rstr, s.Rid)
		}
	}
	return rstr, nil
}

func (c *MainController) RunSshJob() {
	id := c.Ctx.Input.Param(":id")
	if err := jobs.SshBackup(id, false); err != nil {
		fmt.Println(err.Error())
		c.APIReturn(500, "执行失败", err)
	}
	c.APIReturn(200, "执行成功", nil)
}
